package gro.ecorrdata.edata.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import gro.ecorrdata.edata.model.BaseResponse;
import gro.ecorrdata.edata.util.MyUtil;

/**
 * Captcha by huwhois time 2019/11/22
 */
@RestController
@RequestMapping("/admin_user")
public class UserController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // @CrossOrigin
    @RequestMapping("/userinfo")
    public BaseResponse<Map<String, Object>> getuserInfo(Integer id){
        Map<String, Object> result = getUserInfoById(id);

        return new BaseResponse<>(true, "查询成功", result);
    }

    public Map<String, Object> getUserInfoById(Integer id){
        String sql = "select id,role_id,username,email,create_time,status from admin_user where id=?";
        Map<String, Object> result = null;
        try {
            result = jdbcTemplate.queryForMap(sql, id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  result;
    }

    @RequestMapping("/list")
    public BaseResponse<Map<String, Object>> getEDataTableList(Integer page) {
        String sqlTotal =  "select count(*) as total from admin_user where isdel=0 ";
        Map<String, Object> result =  jdbcTemplate.queryForMap(sqlTotal);

        String sql = "select id, role_id, username,pen_name,phone,email,FROM_UNIXTIME(create_time, '%Y-%m-%d') as ctime,status from admin_user where isdel=0 order by id desc limit "+(page-1)*15+", 15";
        try {
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            result.put("list", list);
            Map<String, Object> roleList = getAdminRolesList();
            result.put("roleList", roleList);
            return new BaseResponse<>(true, "查询成功", result);
            
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
            return new BaseResponse<>(true, "查询失败", null);
        }
    }

    public List<Map<String, Object>> getAdminRoles() {
        String sql = "select id, name, permission from admin_role where isdel=0 and status=1 ";
        try {
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            return list;
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
            return null;
        }
    }

    public Map<String, Object> getAdminRolesList() {
        List<Map<String, Object>> list = getAdminRoles();
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map<String,Object> map : list) {
            result.put(map.get("id").toString(), map.get("name"));
        }
        return result;
    }

    @RequestMapping("/getrole")
    public BaseResponse<List<Map<String, Object>>> getRole() {
        List<Map<String, Object>> list = getAdminRoles();
        
        return new BaseResponse<>(true, "查询成功", list);
    }

    @RequestMapping("/getuser")
    public BaseResponse<Map<String, Object>> getUser(Integer id){
        String sql = "select id,role_id,username,pen_name,phone,email,status,note from admin_user where id=?";
      
        try {
            Map<String, Object> result = jdbcTemplate.queryForMap(sql, id);
            List<Map<String, Object>> roleList = getAdminRoles();
            result.put("roleList", roleList);

            return new BaseResponse<>(true, "查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }
    }

    @RequestMapping("/add")
    @PostMapping
    public BaseResponse<Object> addUser(HttpServletRequest request) {
        boolean result = false;
        String username = request.getParameter("username");
        String role_id = request.getParameter("role_id");
        if (username==null || username== "" || role_id==null || role_id=="") {
            return new BaseResponse<>(false, "用户名、角色名不能为空", null);
        }

        Integer rid = Integer.parseInt(role_id);
        String password = (request.getParameter("password")==null || request.getParameter("password")=="") ? MyUtil.md5("123456") : MyUtil.md5(request.getParameter("password"));
        String pen_name = (request.getParameter("pen_name")==null || request.getParameter("pen_name")=="") ? "" : request.getParameter("pen_name");
        String phone = (request.getParameter("phone")==null || request.getParameter("phone")=="") ? "" : request.getParameter("phone");
        String email = (request.getParameter("email")==null || request.getParameter("email")=="") ? "" : request.getParameter("email");
        String note = (request.getParameter("note")==null || request.getParameter("note")=="") ? "" : request.getParameter("note");
        Long ctime = (Long) (System.currentTimeMillis()/1000);

        String sqlUNum = "select count(*) as num from admin_user where `username`= '"+username+"'";
        Map<String, Object> uResult = jdbcTemplate.queryForMap(sqlUNum);
        if (uResult!=null && (Long) uResult.get("num") > 0) {
            return new BaseResponse<>(false, "用户名已存在, 请使用其他用户名", null);
        }
        String sql = "INSERT INTO admin_user(role_id, username, password, pen_name, phone, email, create_time, note) VALUES(?,?,?,?,?,?,?,?)";

        int itemp = jdbcTemplate.update(sql,new Object[]{rid, username, password, pen_name, phone, email, ctime, note});

        if (itemp > 0) {
            result =true;
        }   

        if (result==true) {
            System.out.println("Ok!");
            return new BaseResponse<>(true, "操作成功!", null);
        } else {
            System.out.println("Error!");
            return new BaseResponse<>(false, "操作失败!", null);
        }
    }

    @PostMapping("/update")
    public BaseResponse<Object> updateUser(HttpServletRequest request) {
        boolean result = false;
        String id = request.getParameter("id");
        if (id == null || id=="") {
            String username = request.getParameter("username");
            String role_id = request.getParameter("role_id");
            if (username==null || username== "" || role_id==null || role_id=="") {
                return new BaseResponse<>(false, "用户名、角色名不能为空", null);
            }

            Integer rid = Integer.parseInt(role_id);
            String password = (request.getParameter("password")==null || request.getParameter("password")=="") ? MyUtil.md5("123456") : MyUtil.md5(request.getParameter("password"));
            String pen_name = (request.getParameter("pen_name")==null || request.getParameter("pen_name")=="") ? "" : request.getParameter("pen_name");
            String phone = (request.getParameter("phone")==null || request.getParameter("phone")=="") ? "" : request.getParameter("phone");
            String email = (request.getParameter("email")==null || request.getParameter("email")=="") ? "" : request.getParameter("email");
            String note = (request.getParameter("note")==null || request.getParameter("note")=="") ? "" : request.getParameter("note");
            Long ctime = (Long) (System.currentTimeMillis()/1000);

            String sqlUNum = "select count(*) as num from admin_user where `username`= '"+username+"'";
            Map<String, Object> uResult = jdbcTemplate.queryForMap(sqlUNum);
            if (uResult!=null && (Long) uResult.get("num") > 0) {
                return new BaseResponse<>(false, "用户名已存在, 请使用其他用户名", null);
            }
            String sql = "INSERT INTO admin_user(role_id, username, password, pen_name, phone, email, create_time, note) VALUES(?,?,?,?,?,?,?,?)";

            int itemp = jdbcTemplate.update(sql,new Object[]{rid, username, password, pen_name, phone, email, ctime, note});

            if (itemp > 0) {
                result =true;
            }   
        } else {
            String role_id = request.getParameter("role_id");
            if (role_id==null || role_id=="") {
                return new BaseResponse<>(false, "用户名、角色名不能为空", null);
            }

            Integer rid = Integer.parseInt(role_id);
            String pen_name = (request.getParameter("pen_name")==null || request.getParameter("pen_name")=="") ? "" : request.getParameter("pen_name");
            String phone = (request.getParameter("phone")==null || request.getParameter("phone")=="") ? "" : request.getParameter("phone");
            String email = (request.getParameter("email")==null || request.getParameter("email")=="") ? "" : request.getParameter("email");
            String note = (request.getParameter("note")==null || request.getParameter("note")=="") ? "" : request.getParameter("note");
            Long ctime = (Long) (System.currentTimeMillis()/1000);
            String sql = "UPDATE admin_user SET role_id=?, pen_name=?, phone=?, email=?, modify_time=?, note=?  where `id`=?";

            int itemp = jdbcTemplate.update(sql, new Object[]{rid, pen_name, phone,email,ctime,note, id});

            if (itemp > 0) {
                result =true;
            }   
        }

        if (result==true) {
            System.out.println("Ok!");
            return new BaseResponse<>(true, "操作成功!", null);
        } else {
            System.out.println("Error!");
            return new BaseResponse<>(false, "操作失败!", null);
        }
    }

    @RequestMapping("/delete")
    @PostMapping
    public BaseResponse<Object> deleteUser(Integer id) {
        boolean result = false;
        if (id == null) {
            return new BaseResponse<>(false, "找不到要删除的数据", null);
        }

        String sql = "UPDATE admin_user SET `isdel`=1 where `id`=?";
        // System.out.println(sql);
        // System.out.println(id);
        try {
            jdbcTemplate.update(sql, id);
            
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        return new BaseResponse<>(result, "操作成功", null);
    }

    // public boolean checkPermission (Integer id, String url) {
      
    //     // return result;
    //     return true;
    // }

	public boolean checkPermission(Integer userId, String url) {
        boolean result = false;
        String sqlRole = "select role_id from admin_user where id=?";
        Map<String, Object> roleMap= jdbcTemplate.queryForMap(sqlRole, userId);
        Integer rId = Integer.parseInt(roleMap.get("role_id").toString());
        if (rId==1) {
            return true;
        }

        String sqlPermissions = "select permission from admin_role where id=?";
        Map<String, Object> perMap= jdbcTemplate.queryForMap(sqlPermissions, rId);
        String pers = (String) perMap.get("permission");
        // System.out.println(pers);
        // System.out.println(url);

        String[] str = url.split("/");
        if (str.length<4) {
            return false;
        }

        String controller = str[2];
        String method = str[3];

        // System.out.println(controller);
        // System.out.println(method);
        // login 下的 logout 无需 验证(login下所有方法均无需验证)
        if (controller.equals("login")) {
            return true;
        }

        String sqlCon = "select id from permission where method=?";
        try {
            Map<String, Object> conMap= jdbcTemplate.queryForMap(sqlCon, controller);
            String cId = conMap.get("id").toString();
            // System.out.println(conMap);
            if (cId!=null && cId!="" && pers.indexOf(cId) >-1) {
                String sqlMet = "select id from permission where method=? and pid=?";
                try {
                    Map<String, Object> metMap= jdbcTemplate.queryForMap(sqlMet, method, cId);
                    String mId = metMap.get("id").toString();

                    if (mId==null || mId=="" || pers.indexOf(mId) < 0) {
                        result = false;
                    } else {
                        result = true;
                    }
                } catch (Exception e) {
                    //TODO: handle exception
                    e.printStackTrace();
                    result = false;
                }
            } else {
                result = false;
            }
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
            result = false;
        }
        return result;
	}
}
